import { _decorator, Component, EditBox, instantiate, Label, Node, ScrollView } from 'cc';
import { Pomelo } from '../libs/Pomelo';
const { ccclass, property } = _decorator;

@ccclass('ChatView')
export class ChatView extends Component {

    @property(ScrollView)
    chatScrollView: ScrollView = null;

    @property(Node)
    chatItemPrefab: Node = null;

    @property(EditBox)
    chatContent: EditBox = null;

    @property(Label)
    balance: Label = null;

    nickName: string = '';

    start() {
        this.chatScrollView.content.removeAllChildren();

        Pomelo.on('onNewUser', this.onNewUser.bind(this));
        Pomelo.on('onMembers', this.onMembers.bind(this));
        Pomelo.on('onBalance', this.onBalance.bind(this));
        Pomelo.on('onMessage', this.onMessage.bind(this));
    }

    update(deltaTime: number) {
        
    }

    setNickName(nickName: string) {
        this.nickName = nickName;
    }

    createChatItem(user: string, content: string) {
        const chatItem = instantiate(this.chatItemPrefab);
        if (!chatItem) {
            return;
        }

        chatItem.getChildByName('Name').getComponent(Label).string = `${user}: `;
        chatItem.getChildByName('Content').getComponent(Label).string = content;
        chatItem.active = true;
        return chatItem;
    }

    onMessage(msg: { name: string, content: string}) {
        const chatItem = this.createChatItem(msg.name, msg.content);
        this.chatScrollView.content.addChild(chatItem);
        this.chatScrollView.scrollToBottom(0);
    }

    onBtnSendClicked() {

        if (this.chatContent.string.trim() === '') {
            console.error('请输入聊天内容');
            return;
        }

        Pomelo.notify('room.room.syncMessage', {
            name: this.nickName,
            content: this.chatContent.string,
        });

        this.chatContent.string = '';
    }

    onBtnClearClicked() {
        this.chatScrollView.content.removeAllChildren();
    }

    onNewUser(data) {
        const chatItem = this.createChatItem('System', data.content);
        this.chatScrollView.content.addChild(chatItem);
    }

    onMembers() {

    }

    onBalance(data) {
        console.log("onBalance", data)
        this.balance.string = data.currentBalance;
    }

}


